package pers.qianyu.month_202011.date_20201130;

/**
 * 72. 编辑距离
 * https://leetcode-cn.com/problems/edit-distance/
 *
 * @author mizzle rain
 * @date 2020-11-30 14:48
 */
public class MinDistance {
    /**
     * dp table 的含义：word1[0...i] 到 word2[0...j] 的编辑距离
     */
    public int minDistance(String word1, String word2) {
        if ("".equals(word1)) {
            return word2.length();
        }
        if ("".equals(word2)) {
            return word1.length();
        }
        int[][] dp = new int[word1.length() + 1][word2.length() + 1];
        for (int i = 1; i < word1.length() + 1; i++) {
            dp[i][0] = i;
        }
        for (int i = 1; i < word2.length() + 1; i++) {
            dp[0][i] = i;
        }
        dp[0][0] = 0;
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[i].length; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j] + 1,
                            Math.min(dp[i][j - 1] + 1, dp[i - 1][j - 1] + 1));
                }
            }
        }
        return dp[word1.length()][word2.length()];
    }
}
